from google.appengine.ext import db
from app.helpers.queries import Query
from datasets import DataSet, DEFAULT_DATASET
from google.appengine.api.users import User


# A list of all the permission types we allow
PERMISSIONS = {
  'checkout' : 'Upload data',
  'find_one' : 'Search for an individual',
  'download' : 'Download data',
  'fieldsets' : 'Create and update fieldsets'
}


class UserPermission(db.Model):
  """ A Permission for a user to edit values for a dataset """
  user = db.UserProperty()
  dataset = db.ReferenceProperty(DataSet, default=DEFAULT_DATASET)
  permissions = db.StringListProperty()


def add_permissions_for(user, *permissions):
  """ Takes a user or email and a list of strings that act as permissions
  
  >>> from google.appengine.api.users import User
  >>> user = User(email=u'squirrel.appengine@gmail.com')
  
  >>> up = add_permissions_for(user, u'hello', u'world')
  >>> up.user.email()
  u'squirrel.appengine@gmail.com'
  >>> assert 'hello' in up.permissions, up.permissions
  >>> assert 'world' in up.permissions, up.permissions
  
  >>> up = add_permissions_for(user, u'hello', u'again')
  >>> up.user.email()
  u'squirrel.appengine@gmail.com'
  >>> assert 'hello' in up.permissions, up.permissions
  >>> assert 'world' in up.permissions, up.permissions
  >>> assert 'again' in up.permissions, up.permissions
  
  >>> up = add_permissions_for('a_user@gmail.com', u'hello', u'world')
  >>> up.user.email()
  u'a_user@gmail.com'
  >>> assert 'hello' in up.permissions, up.permissions
  >>> assert 'world' in up.permissions, up.permissions
  
  Clean up
  >>> db.delete(UserPermission.all())
  
  """
  if not isinstance(user, User): user = User(email=user)
  user_permission = UserPermission.get_or_insert(
    key_name='k'+user.email(), user=user)
  
  permissions = list(permissions)
  permissions += user_permission.permissions
  permissions = list(set(permissions)) # Make unique
  
  user_permission.permissions = permissions
  user_permission.put()
  
  return user_permission


def get_permissions_for(user):
  """ Gets permissions list for a user
  
  >>> from google.appengine.api.users import User
  >>> user = User(email=u'squirrel.appengine@gmail.com')
  >>> up = add_permissions_for(user, u'hello', u'world')
  
  >>> permissions = get_permissions_for(user)
  >>> assert 'hello' in permissions, permissions
  >>> assert 'world' in permissions, permissions
  
  """
  up = Query(UserPermission).filter('user =', user).fetch()
  if up:
    return up.permissions
  else:
    return []
